package rpc07;


import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.hl.rpc.service.IProdService;
import com.hl.rpc.service.IUserService;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * Created by yuanhailong on 2021/10/30.
 */
public class Server {

    private static boolean running=true;

    private static HashMap<String ,Class> regiester=new HashMap<>();

    public static void main(String[] args) throws Exception{


        //模拟注册
        regiester();

        ServerSocket serverSocket=new ServerSocket(9999);


        System.out.println("rpc07 服务端启动...");
        while (running){
            Socket socket=serverSocket.accept();
            process(socket);
            socket.close();
        }
        serverSocket.close();
    }





    private static void process(Socket socket) throws Exception{
        Hessian2Input ois = new Hessian2Input(socket.getInputStream());
        Hessian2Output oos = new Hessian2Output(socket.getOutputStream());

        String className = ois.readString();
        String methodName = ois.readString();
        Class[] paramTypes=(Class[])ois.readObject();
        Object[] args=(Object[])ois.readObject();
        System.out.println("服务端调用方法的方法名:"+methodName);
        System.out.println("服务端调用类名:"+className);

        //从注册中心查找
        Class clazz= regiester.get(className);

        Method method = clazz.getMethod(methodName, paramTypes);
        Object  object= method.invoke(clazz.newInstance(), args);//返回任意对象
        oos.writeObject(object);
        oos.flush();
    }

    /**
     * 这一部分应该采用服务注册，比如zookeeper等
     */
    private static void regiester(){
        regiester.put(IUserService.class.getName(), UserServiceImp.class);
        regiester.put(IProdService.class.getName(), ProdServiceImp.class);
    }

}
